import time
import os
import sys
import logging
from common.watched_rotating_log import WatchedRotatingFileHandler
from os.path import dirname, abspath

PATH=dirname(dirname(abspath(__file__))) + '/log/work'

g_logger = {}

class Logger:

    def __init__(self, name, size = 50, backupCount = 10,
                 cacheRecords = 5, print_to_console=False):
        '''
        dtformat: 日期格式化，默认是空
        size : 单个日志文件的大小，单位是M。
        backupCount :备份的最大日志文件数'
        cacheRecords :日志缓存数。达到该数字才会写硬盘。flushLevel以上级别的除外
        '''
        self.logger = logging.getLogger(name)
        self.logger.setLevel(logging.DEBUG)
        logfile = os.path.join(PATH, name)
        hdlr = WatchedRotatingFileHandler(logfile, 'a', maxBytes=1024*1024 *size, backupCount=backupCount)
        hdlr.setFormatter(logging.Formatter('%(asctime)s [%(threadName)s:%(thread)d] [%(name)s:%(lineno)d] [%(module)s:%(funcName)s] [%(levelname)s]- %(message)s'))
        self.logger.addHandler(hdlr)
        if print_to_console:
            #将大于或等于DEBUG级别的信息输出到控件台
            hdlr = logging.StreamHandler(sys.stdout)
            hdlr.setFormatter(logging.Formatter('%(asctime)s [%(threadName)s:%(thread)d] [%(name)s:%(lineno)d] [%(module)s:%(funcName)s] [%(levelname)s]- %(message)s', ''))
            hdlr.setLevel(logging.DEBUG)
            self.logger.addHandler(hdlr)

    def getLogger(self):
        return self.logger

    @staticmethod
    def new(name, dtformat="%Y-%m-%d"):
        new_name = "{0}_{1}".format(name, time.strftime(dtformat))
        if new_name in g_logger:
            return g_logger[new_name]
        g_logger[new_name] = Logger(new_name).logger
        return g_logger[new_name]


if __name__ == "__main__":
    for _ in range(1000):
        log = Logger.new("access.log")
        log.info("xxx")